package com.sky.controller.user;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.result.Result;
import com.sky.service.AddressBookService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/user/addressBook")
@Api(tags = "c端地址簿功能相关接口")
public class AddressBookController {
    @Autowired
    private AddressBookService addressBookService;

    /**
     * 添加地址簿
     *
     * @param addressBook
     * @return
     */
    @PostMapping()
    @ApiOperation("添加地址簿")
    public Result addAddressBook(@RequestBody AddressBook addressBook) {
        Long userId = BaseContext.getCurrentId();
        log.info("用户id:{}添加一条地址", userId);
        addressBookService.add(addressBook);
        return Result.success();
    }

    /**
     * 查询当前用户的所有地址簿信息
     *
     * @return
     */
    @ApiOperation("查询当前用户的所有地址簿信息")
    @GetMapping("/list")
    public Result<List<AddressBook>> queryByUserId() {
        int type = -1;
        List<AddressBook> list = addressBookService.list(type);
        return Result.success(list);
    }

    /**
     * 查询当前用户默认地址信息
     *
     * @return
     */
    @ApiOperation("查询默认地址信息")
    @GetMapping("/default")
    public Result<AddressBook> queryByDefault() {
        int type = -2;
        List<AddressBook> list = addressBookService.list(type);
        return Result.success(list.get(0));
    }

    /**
     * 根据id查询信息
     *
     * @param id
     * @return
     */
    @ApiOperation("根据id查询地址信息")
    @GetMapping("/{id}")
    public Result<AddressBook> queryByUserId(@PathVariable Integer id) {
        List<AddressBook> list = addressBookService.list(id);
        return Result.success(list.get(0));
    }

    /**
     * 根据id修改地址簿信息
     *
     * @param addressBook
     * @return
     */
    @ApiOperation("根据id修改地址簿信息")
    @PutMapping()
    public Result modifyAddressBook(@RequestBody AddressBook addressBook) {
        addressBookService.modifyById(addressBook);
        return Result.success();
    }

    /**
     * 根据id删除地址簿信息
     *
     * @param id
     * @return
     */
    @DeleteMapping
    @ApiOperation("根据id删除地址簿信息")
    public Result deleteAddressBookById(@RequestParam Long id) {
        Long userId = BaseContext.getCurrentId();
        log.info("用户id:{}删除了一条地址信息", userId);
        addressBookService.deleteById(id);
        return Result.success();
    }

    /**
     * 根据id设置默认地址
     *
     * @param addressBook
     * @return
     */
    @ApiOperation("根据id设置默认地址")
    @PutMapping("/default")
    public Result setDefault(@RequestBody AddressBook addressBook) {
        Long userId = BaseContext.getCurrentId();
        log.info("用户id{}:设置默认地址", userId);
        addressBookService.setDefaultAddressBook(addressBook);
        return Result.success();
    }
}
